package com.yzg.redis.web.controller;

import com.yzg.redis.manager.RedisManager;
import com.yzg.redis.service.HqStationService;
import com.yzg.redis.vo.HqBaseVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/1/16.
 */
@Controller
@RequestMapping("/redis")
public class RedisController {
    private transient final Logger log = LoggerFactory.getLogger(getClass());

    @Resource
    private RedisManager redisManager;

    @Resource
    private HqStationService hqStationService;

    @RequestMapping(value = "/addHqList",method = RequestMethod.POST)
    @ResponseBody
    public String updatedKey(HttpServletRequest request, @RequestParam(value = "HQId") String HQId) throws Exception {
        List<HqBaseVO> hqBaseList = hqStationService.getHqBaseList();
        HqBaseVO hqBaseVO = new HqBaseVO();
        final Field[] declaredFields = hqBaseVO.getClass().getDeclaredFields();
        List<String> fieldNameList = new ArrayList<>();
        for (Field declaredField : declaredFields) {
            final String fieldName = declaredField.getName();
            if(!"serialVersionUID".equals(fieldName)){
                fieldNameList.add(fieldName);
            }
        }

        for (HqBaseVO hqBase : hqBaseList) {
            for (String fieldName : fieldNameList) {
                String methodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1, fieldName.length());
                final Method method = hqBase.getClass().getMethod(methodName);
                final Object methodValue = method.invoke(hqBase);
                String fieldValue = null;
                if(methodValue!=null||"".equals(methodValue)){
                    fieldValue = methodValue.toString();
                }
                redisManager.setHSet(hqBase.getHqId(),fieldName,fieldValue);
                final String redisKeyValue = redisManager.getHSet(hqBase.getHqId(), fieldName);
                log.info("updatedKey return  is : " +fieldName+" : "+redisKeyValue);

            }
        }
        return HQId;

    }


}
